package com.base.library.widget;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.tencent.smtt.export.external.interfaces.GeolocationPermissionsCallback;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by ChengZhi on 2017/4/16.
 */

public class WebViewBase extends WebView {
    public WebViewBase(Context context) {
        super(context);
        initView(context);
    }

    public WebViewBase(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        initView(context);
    }

    public WebViewBase(Context context, AttributeSet attributeSet, int i) {
        super(context, attributeSet, i);
        initView(context);
    }

    public WebViewBase(Context context, AttributeSet attributeSet, int i, boolean b) {
        super(context, attributeSet, i, b);
        initView(context);
    }

    public WebViewBase(Context context, AttributeSet attributeSet, int i, Map<String, Object> map, boolean b) {
        super(context, attributeSet, i, map, b);
        initView(context);
    }

    private void initView(Context context) {

        getSettings().setJavaScriptEnabled(true);//JS
        requestFocus();
        getSettings().setDefaultTextEncodingName("utf-8");
        getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
        getSettings().setDatabaseEnabled(true);
        getSettings().setUseWideViewPort(true);
        getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        String dir = context.getDir("database", Context.MODE_PRIVATE).getPath();
        //启用地理定位
        getSettings().setGeolocationEnabled(true);
        //设置定位的数据库路径
        getSettings().setGeolocationDatabasePath(dir);
        //最重要的方法，一定要设置，这就是出不来的主要原因
        getSettings().setDomStorageEnabled(true);
        setWebListener(context);
        setFocusableInTouchMode(true);
        getSettings().setPluginsEnabled(true);
        setHorizontalScrollBarEnabled(false);//水平不显示
        setVerticalScrollBarEnabled(false); //垂直不显示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setWebContentsDebuggingEnabled(true);
        }
    }

    private void setWebListener(Context mContext) {
        setWebChromeClient(new CompetitionWebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO Auto-generated method stub
                super.onProgressChanged(view, newProgress);

            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissionsCallback callback) {
                callback.invoke(origin, true, false);
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }

            @Override
            public void onShowCustomView(View view, IX5WebChromeClient.CustomViewCallback customViewCallback) {
                super.onShowCustomView(view, customViewCallback);
            }
        });

        setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub

                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//                handler.proceed();  // 接受所有网站的证书 error);
            }


            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("alipays:") || url.startsWith("alipay")) {
                    try {
                        view.getContext().startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                    } catch (Exception e) {
                        new AlertDialog.Builder(view.getContext())
                                .setMessage("未检测到支付宝客户端，请安装后重试。")
                                .setPositiveButton("立即安装", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Uri alipayUrl = Uri.parse("https://d.alipay.com");
                                        view.getContext().startActivity(new Intent("android.intent.action.VIEW", alipayUrl));
                                    }
                                }).setNegativeButton("取消", null).show();
                    }
                    return true;
                }
                if (url.startsWith("weixin://")) {
                    try {
                        view.getContext().startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                    } catch (Exception e) {
                        Toast.makeText(view.getContext(), "未检测到微信客户端，请安装后重试。", Toast.LENGTH_LONG).show();
                    }
                    return true;
                }
                if (url != null) {
                    Uri uri = Uri.parse(url);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    if (url.startsWith("dinree://")) {
                        intent.putExtra("url", url.replace("dinree://", "http://"));
                    } else if (url.startsWith("dinreesearch://")) {
                        intent.putExtra("url", url.replace("dinreesearch://", "http://"));
                    } else if (url.startsWith("dinreecart://")) {
                        intent.putExtra("url", url.replace("dinreecart://", "http://"));
                    } else if (url.startsWith("dinreegoods://")) {
                        intent.putExtra("url", url.replace("dinreegoods://", "http://"));
                    } else if (url.startsWith("dinreeaddress://")) {
                        intent.putExtra("url", url.replace("dinreeaddress://", "http://"));
                    } else if (url.startsWith("dinreecoupon://")) {
                        intent.putExtra("url", url.replace("dinreecoupon://", "http://"));
                    } else if (url.startsWith("tel:")) {
                        view.getContext().startActivity(intent);
                        return true;
                    } else {
                        Map<String, String> extraHeaders = new HashMap<String, String>();
                        extraHeaders.put("referer", "https://web.dinree.cn/epsea/front");
                        loadUrl(url, extraHeaders);
                        return true;
                    }
                    view.getContext().startActivity(intent);
                }
                return true;
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {

                super.onReceivedError(view, errorCode, description, failingUrl);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                // TODO Auto-generated method stub
                super.onPageFinished(view, url);

            }
        });

        setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Uri uri = Uri.parse(url);
//                RouterManager.goActivity(mContext, uri);
            }
        });
    }

    private Object getHtmlObject() {
        Object insertObj = new Object() {
            // 点击js回调
            @JavascriptInterface
            public void xxxxxx(final String phone_name) {

            }
        };
        return insertObj;
    }
}

